package net.tribal.comic.entities

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
import org.joda.time.*

class User {
	//	Persistence Attributes
	String 	alias
	String 	name
	String 	lastName
	String 	email
	String	gender
    String  password
    Date 	birdDay
    String  country
    String 	nameFile
    
    boolean admin 		= false
    boolean rateable 	= true
	boolean commentable = true
	boolean disabled 	= false	

	Date 	dateCreated
	Date 	lastUpdated
	
	
	//	Not Persistence Attributes
	Float rate
	String pathFile
	String fullName
	String age
	String  repeatPassword
	static transients = ['rate', 'pathFile', 'fullName', 'age', 'repeatPassword']
	
	
	//	DB Relations
	static 	hasMany = 	[favoritesComics	: Comic,
	       	          	 comments			: Comment,
	       	          	 ratings			: Rate]
	
	       	          	 
	//	DB Constraits
	static constraints = {
		name(blank:false)
		lastName(blank:false)
		alias(blank:false)	
		email(blank:false,email:true)
        password(size:5..15,blank:false)
        nameFile(blank:true, nullable:true)
	}
	
	
	//	Other Methods
	String getRate() {
		//	Calculem la mitja de les puntuacions rebudes fins ara
		Float p = 0
		if(ratings){
			ratings.each(){ p += it.rate }
			p = p / ratings.count()
		}
		return p
	}
	
	String getPathFile() {
		def p = ""
		if (nameFile == null || nameFile == "") {
			nameFile = "avatar${gender}.jpg"
			return "images/"
		}
		return "uploads/user/"
	}
	
	String getFullName() {
		def fullName = ""
		if(lastName) { fullName = lastName.plus(", ") }
		fullName += name
		return fullName
	}
	
	String getAge() {
		return String.valueOf( Years.yearsBetween( new DateTime( birdDay.getTime() ), new DateTime( new Date().getTime() ) ).getYears() )
	}
}